<?php
/**
 * Created by PhpStorm.
 * User: Huyang
 * Date: 2016/9/28
 * Time: 14:36
 */

namespace App\Http\Repositories\Services\Impls;


use App\Exceptions\ServiceException;
use App\Http\Constants\CommonExceptionConstants;
use App\Http\Constants\ServiceExceptionConstants;
use App\Http\Repositories\Daos\IUserDao;
use App\Http\Repositories\Eloquent\User;
use App\Http\Repositories\Services\IUser;
use App\Http\Requests\Admin\UserInputDTO;
use App\Http\Requests\Admin\UserRoleInputDTO;

class UserService implements IUser
{

    protected $userDao;

    public function __construct(
        IUserDao $userDao
    )
    {
        $this->userDao = $userDao;
    }

    public function byId($id) {
        $dao = $this->userDao->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::getKey('no_find_data'));
        }
        return $dao;
    }

    public function lists($search,$page, $size) {
        return $this->userDao->lists($search,$page, $size);
    }

    public function store(UserInputDTO $inputDTO)
    {
        $dao = new User();
        $dao->nickname = $inputDTO->get('nickname');
        $dao->username = $inputDTO->get('username');
        $dao->password =  bcrypt($inputDTO->get('password'));
        $dao->save();
    }

    public function update(UserInputDTO $inputDTO, $id)
    {
        $dao = $this->userDao->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::getKey('no_find_data'));
        }
        $dao->nickname = $inputDTO->get('nickname');
        $dao->username = $inputDTO->get('username');
        if ($inputDTO->get('password')) {
            $dao->password =  bcrypt($inputDTO->get('password'));
        }
        $dao->save();
    }

    public function job($id,$state){
        $dao = $this->userDao->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::getKey('no_find_data'));
        }
        $dao->is_job = $state;
        $dao->save();
    }

    public function role(UserRoleInputDTO $inputDTO, $id)
    {
        $dao = $this->userDao->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::getKey('no_find_data'));
        }
        $roles = $inputDTO->get('role',[]);
        if (!$dao->syncRoles($roles)) {
            throw new ServiceException(ServiceExceptionConstants::getKey('set_fail'));
        }
    }

}